<?php

namespace System\Loader;

/**
 * 路径别名类
 * 
 * @package Dream
 * @subpackage PathAlias
 * @namespace System\Loader
 * @author lewis (lewisld@yeah.net)
 */
class PathAlias
{

    /**
     * 所有路径别名
     * 
     * @static
     *
     * @access protected
     * @var array
     */
    protected static $pathList = [];

    /**
     * 注册路径别名
     * 
     * @static
     *
     * @access public
     * @param string|array $alias 路径别名名称，可以是字符串或数组
     * @param string $path 路径别名指向的路径
     * @return void 没有返回值
     */
    public static function registerPath($alias, $path)
    {
        if (is_array($alias)) {
            foreach ($alias as $key => $value) {
                if (NULL != $value) {
                    $key = ('@' !== substr($alias, 0, 1)) ? '@' . $key : $key;
                    $key = preg_replace('/\/+/', '.', str_replace('\\', '/', $key));
                    $value = preg_replace('/\/+/', DS, str_replace('\\', '/', $value));
                    $value = self::getPathAlias($value);
                    self::$pathList[$key] = (string) $value;
                }
            }
            unset($key, $value);
        } else {
            if (NULL != $path) {
                $alias = ('@' !== substr($alias, 0, 1)) ? '@' . $alias : $alias;
                $alias = preg_replace('/\/+/', '.', str_replace('\\', '/', $alias));
                $path = preg_replace('/\/+/', DS, str_replace('\\', '/', $path));
                $path = self::getPathAlias($path);
                self::$pathList[$alias] = (string) $path;
            }
        }
    }

    /**
     * 获取路径别名
     * 
     * @static
     *
     * @access public
     * @param string $alias 路劲别名
     * @return string 别名存在就返回别名指向的路径，否则返回原始信息
     */
    public static function getPath($alias)
    {
        $alias = preg_replace('/\/+/', '.', str_replace('\\', '/', $alias));
        if ('@' !== substr($alias, 0, 1)) {
            return $alias;
        }
        $arr = explode('.', $alias);
        $name = [];
        $count = count($arr) - 1;
        for ($i = 0; $i < $count; $i ++) {
            $name[] = array_pop($arr);
            $str = implode('.', $arr);
            if (isset(self::$pathList[$str])) {
                unset($alias, $arr, $name, $str, $count);
                
                return self::$pathList[$str] . DS . implode(DS, array_reverse($name));
            }
        }
        unset($alias, $arr, $name, $str, $count);
        
        return $alias;
    }

    /**
     * 获取所有路径别名
     * 
     * @static
     *
     * @access public
     * @return array 返回所有别名数组
     */
    public static function getAllPath()
    {
        return self::$pathList;
    }
}
